package com.example.user3.demo;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;


import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.gifdecoder.GifDecoder;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;


public class WaterLayout extends FrameLayout {
        Context context;
        TextView countText;
        TextView water_layout_number_text;
        WaterCircleProgressView  mProgressBar;
        View view;
        public static final int DURATION=5;
        public int duration =DURATION*1000;
        public int interval =DURATION*10;
        ImageView imageView;
        FrameLayout layoutWater;
    public WaterLayout(Context context) {
        super(context);
        this.context=context;
        this.initView();
    }

    public CallBackListener getCallBackListener() {
        return callBackListener;
    }

    public void setCallBackListener(CallBackListener callBackListener) {
        this.callBackListener = callBackListener;
    }

    CallBackListener callBackListener;
    int count;
    public interface CallBackListener {
        void onPerFinish(int count);//完成一圈调度

        void clickWater();
    }


    public WaterLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        initView();
    }

    public WaterLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void initView() {
        view = LayoutInflater.from(context).inflate(R.layout.layout_water, null);
//        LinearLayout linearLayout=view.findViewById(R.id.content);
//        DragRelativeLayout dragRelativeLayout =view.findViewById(R.id.drag);
//        dragRelativeLayout.addDragChildView(linearLayout);
        layoutWater=view.findViewById(R.id.layout_water);

        water_layout_number_text=view.findViewById(R.id.water_layout_number_text);
        countText = view.findViewById(R.id.gift_lianji_text);
        water_layout_number_text = view.findViewById(R.id.water_layout_number_text);
        imageView=view.findViewById(R.id.gif);
        mProgressBar = view.findViewById(R.id.progress);
        addView(view,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        water_layout_number_text.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                onPause();
            }
        });
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(callBackListener!=null){
                    callBackListener.clickWater();
                }
            }
        });

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//        int h = View.MeasureSpec.makeMeasureSpec(0,
//                View.MeasureSpec.UNSPECIFIED);
//
//        measure(w, h);
//        viewWidth = getMeasuredWidth();

    }


    CountDownTimerCopyFromAPI26 timer = null;
    public void annimatorIn() {
        if(timer != null) timer.cancel();
//        setVisibility(View.VISIBLE);
        countText.setVisibility(View.INVISIBLE);
        timer = new CountDownTimerCopyFromAPI26(duration+10, interval) {
            @Override
            public void onTick(long millisUntilFinished) {
//                countText.setText(String.valueOf((millisUntilFinished / 100)+1));
//                Log.i("zzy",millisUntilFinished/duration+"--");
                double f1 = new BigDecimal((float)millisUntilFinished/duration).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                int per= (int) ((1-f1)*100);
                mProgressBar.setProgress(per);
            }

            @Override
            public void onFinish() {
                Log.e("zzy", "onFinish");
                if(callBackListener!=null){
                    callBackListener.onPerFinish(count);
                }
//                annimatorOut();
            }
        }.start();

//        view.setOnClickListener(click);
    }
    public static int GIF_SUCCESS=1;
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==GIF_SUCCESS){
                if(count==6){
                    count=0;
                }
                count=count+1;
//                annimatorIn();
                incomeText(count+"");
//                water_layout_number_text.setText(""+count+"/6");
            }
        }
    };
    public void annimatorOut() {
        if(timer != null) timer.cancel();

//        handler.sendEmptyMessageDelayed(GIF_SUCCESS,3000);
//        setVisibility(View.GONE);
        Log.i("WaterLayout","annimatorOut");
        Glide.with(this).asGif().load(R.drawable.s)
                .listener(requestListener).into(imageView);
    }

    /*---------------------------------------------------------------------------------------------*/
    /**
     * 通过字段名从对象或对象的父类中得到字段的值
     * @param object 对象实例
     * @param fieldName 字段名
     * @return 字段对应的值
     * @throws Exception
     */
    public static Object getValue(Object object, String fieldName) throws Exception {
        if (object == null) {
            return null;
        }
        if (TextUtils.isEmpty(fieldName)) {
            return null;
        }
        Field field = null;
        Class<?> clazz = object.getClass();
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                return field.get(object);
            } catch (Exception e) {
                //这里甚么都不要做！并且这里的异常必须这样写，不能抛出去。
                //如果这里的异常打印或者往外抛，则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了
            }
        }

        return null;
    }


    private void incomeText(String text){
        countText.setVisibility(View.VISIBLE);
        countText.setText(text);
        AnimatorSet animatorSet = new AnimatorSet();
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(countText, "translationY",50,0 );
        objectAnimator.setDuration(400);
        ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(countText, "alpha",0f,1f );
        objectAnimator2.setDuration(400);
        animatorSet.play(objectAnimator).with(objectAnimator2);
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                annimatorIn();
            }
        });
        animatorSet.start();
//        annimatorIn();
    }

    //停止
    public void stop(){
        if(timer != null) timer.cancel();
        timer=null;
    }
    //暂停
    public void onPause(){
        if(timer != null)timer.pause();
    }
    //播放
    public void onResume(){
        if(timer != null) timer.rePalay();
    }
    RequestListener requestListener=new RequestListener<GifDrawable>() {
        int duration = 0;
        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<GifDrawable> target, boolean isFirstResource) {
            return false;
        }

        @Override
        public boolean onResourceReady(GifDrawable gifDrawable, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) {
            try {
                if(duration==0){
                    gifDrawable.setLoopCount(1);
//                    gifDrawable.start();
                    // 计算动画时长
                    //GifDecoder decoder = gifDrawable.getDecoder();//4.0开始没有这个方法了
                    Drawable.ConstantState state = gifDrawable.getConstantState();
                    if(state!=null){
                        //不能混淆GifFrameLoader和GifState类
                        Object gifFrameLoader = getValue(state,"frameLoader");
                        Log.e("Glide4.0","getValue:"+duration);
                        if(gifFrameLoader!=null){
                            Object decoder = getValue(gifFrameLoader,"gifDecoder");
                            if(decoder!=null && decoder instanceof GifDecoder){
                                for (int i = 0; i < gifDrawable.getFrameCount(); i++) {
                                    duration += ((GifDecoder) decoder).getDelay(i);
                                }
                            }
                        }
//                        gifDrawable.stop();
                        Log.e("Glide4.0","gif播放动画时长duration:"+duration);
                        handler.sendEmptyMessageDelayed(GIF_SUCCESS,duration);

                    }
                }else{
                    handler.sendEmptyMessageDelayed(GIF_SUCCESS,duration);
                }

            } catch (Throwable e) {
            }


            return false;
        }
    };

}
